package com.panda.order.guanjiapo.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.panda.order.guanjiapo.Config;
import com.panda.order.guanjiapo.entity.UploadSaleOrdersRequest;
import com.panda.order.guanjiapo.entity.uploadorder.SaleOrderEntity;
import com.panda.order.guanjiapo.utils.AESCoder;
import com.panda.order.guanjiapo.utils.HttpRequest;

import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UploadSaleordersApi {

    public String doUploadSaleOrders(List<SaleOrderEntity> tGjpOrders)  throws Exception
    {
        String ret = "";
        //业务参数获取
        UploadSaleOrdersRequest order = new UploadSaleOrdersRequest();
        List<SaleOrderEntity> orders = JSONArray.parseArray(JSON.toJSONString(tGjpOrders), SaleOrderEntity.class);
        order.setOrders(orders);
        //接口调用参数组装
        Map<String, String> param;
        try {
            // 获取token
            ApiGetToken apiGetToken = new ApiGetToken();
            String token = apiGetToken.doGetToken();
            param = GetPostParams(order, token, Config.appkey, Config.sign_key);
            //post报文
            String postString = "";
            for (String in : param.keySet()) {
                postString += in + "=" + URLEncoder.encode(param.get(in),"utf-8")  +"&";
            }
            postString = postString.substring(0, postString.length() - 1);
            ret =  HttpRequest.sendPost(Config.api_link, postString);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }

    public static Map<String, String> GetPostParams(UploadSaleOrdersRequest order, String token, String appKey, String signKey) throws NoSuchAlgorithmException
    {
        Map<String, String> txtParams = new HashMap<String, String>();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        Date now = new Date();
        String time = dateFormat.format(now);

        //添加业务参数
        BuildOrderParams(order, txtParams);
        // 添加系统参数
        txtParams.put("method", order.GetApiName());
        txtParams.put("appkey", appKey);
        txtParams.put("timestamp", time);
        txtParams.put("token", token);
        //签名参数
        AESCoder coder = new AESCoder();
        txtParams.put("sign", coder.SignRequest(txtParams, signKey));
        return txtParams;
    }

    public static void BuildOrderParams(UploadSaleOrdersRequest order, Map<String, String> parameters)
    {
        parameters.put("shopkey", Config.shop_key);
        parameters.put("orders",  JSONArray.toJSONString(order.getOrders()));

    }

}
